import { CSSProperties, ReactNode, useRef } from 'react'
import { useSize } from 'ahooks'
import { Input, Popover, theme } from 'antd'
import type { TextAreaRef } from 'antd/es/input/TextArea'
import { CloseCircleFilled } from '@ant-design/icons'

interface ITextAreaFilterProps {
  style?: CSSProperties
  className?: string
  id?: string
  size?: 'small' | 'middle' | 'large'
  placeholder?: string
  textAreaPlaceholder?: string
  textAreaExtra?: ReactNode
  value?: string
  onChange?: (value: string) => void
}

/** 多行文本筛选条件 */
export const TextAreaFilter = ({
  style,
  className,
  id,
  size,
  placeholder,
  textAreaPlaceholder,
  textAreaExtra,
  value,
  onChange,
}: ITextAreaFilterProps) => {
  const { token } = theme.useToken()
  const textAreaRef = useRef<TextAreaRef>(null)
  const divRef = useRef<HTMLDivElement>(null)
  const divSize = useSize(divRef)

  let showValue: string | undefined
  const list = value?.trim().split(/\s*\n+\s*/)
  if (list?.length) {
    showValue = list[0]
    if (list.length > 1) showValue += `(${list.length})`
  }

  return (
    <Popover
      arrow={false}
      placement="bottomLeft"
      trigger="click"
      overlayStyle={{ minWidth: 220, width: divSize?.width }}
      content={
        <>
          <Input.TextArea
            ref={textAreaRef}
            style={{ resize: 'none' }}
            placeholder={textAreaPlaceholder}
            rows={6}
            autoSize={false}
            value={value}
            onChange={e => onChange?.(e.target.value)}
            onBlur={e => {
              const newVal = e.target.value.trim().replace(/\s*\n+\s*/g, '\n')
              if (newVal !== e.target.value) {
                e.target.value = newVal
                onChange?.(newVal)
              }
            }}
          />
          {!!textAreaExtra && (
            <div style={{ marginTop: 4, textAlign: 'right', fontSize: '0.9em', color: token.colorTextQuaternary }}>
              {textAreaExtra}
            </div>
          )}
        </>
      }
      afterOpenChange={open => {
        if (open) textAreaRef.current?.focus()
      }}
    >
      <div ref={divRef} style={{ width: 200, ...style }} className={className} id={id}>
        <Input
          size={size}
          placeholder={placeholder}
          readOnly
          value={showValue}
          allowClear={false}
          suffix={
            showValue ? (
              <span className="ant-input-clear-icon" onClick={e => e.stopPropagation()}>
                <CloseCircleFilled
                  onClick={() => {
                    onChange?.('')
                    textAreaRef.current?.focus()
                  }}
                />
              </span>
            ) : (
              <></>
            )
          }
        />
      </div>
    </Popover>
  )
}
